<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btn-list="fullInfo.btnList"
      @returnBack="$emit('returnModify')"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
            @handleEvent="changeHandle"
          >
            <template v-slot:form-supplierName>
              <el-input
                type="input"
                :disabled="true"
                :class="'not-mongolia'"
                placeholder="请选择供应商"
                v-model="formInfo.data.supplierName"
              >
                <template #append>
                  <el-icon @click="openSupplierWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-address>
              <el-input
                v-model="formInfo.data.address"
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择收货地址"
              >
                <template #append>
                  <el-icon @click="openReceiveAddressWindow"
                    ><MoreFilled
                  /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')"></Tooltip>
        </div>
        <div class="model-panel-body">
          <div class="filter-wrapper">
            <!-- 条件栏 -->
            <page-filter
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            >
              <template v-slot:filter-addProduct>
                <el-button :disabled="canAddProduct" @click="addProduct"
                  >手动新增</el-button
                >
              </template>
              <template v-slot:filter-importPurchOrder>
                <el-button
                  :disabled="canAddImportProduct"
                  @click="importPurchOrder"
                  >引用系统采购单</el-button
                >
              </template>
              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除产品</el-button
                >
              </template>
            </page-filter>
            <div class="display-flex">
              <el-button v-if="!toSummaryFlag" @click="toSummaryFlag = true"
                >汇总页</el-button
              >
              <el-button v-else @click="toSummaryFlag = false"
                >订单页</el-button
              >
            </div>
          </div>
          <div class="flex_full_item">
            <el-form
              v-if="!toSummaryFlag"
              ref="tableForm"
              :model="tableInfo"
              style="width: 100%"
            >
              <!-- 表格 -->
              <page-table
                ref="table"
                class="table-scroll-hidden"
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :tab-index="false"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-qty="scope">
                  <el-form-item class="margin-bottom">
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.qty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positive,
                                      trigger: ['blur', 'change'],
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.qty"
                              clearable
                              controls-position="right"
                              :precision="systemConfig.qty_show_precision"
                              @change="
                                changeLarge($event, `data.${scope.$index}.qty`)
                              "
                              :min="0"
                              :max="largeMax(scope.row)"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.networkUnit }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-form-item>
                </template>
                <template v-slot:col-networkUnitScale="scope">
                  {{
                    scope.row.systemUnitCoefficient +
                    scope.row.unitName +
                    '=' +
                    scope.row.networkUnitCoefficient +
                    scope.row.networkUnit
                  }}
                </template>
                <template v-slot:col-provinceAvailableQty="scope">
                  <span
                    v-if="
                      scope.row.provinceAvailableQty ||
                      scope.row.provinceAvailableQty === 0
                    "
                  >
                    {{ scope.row.provinceAvailableQty + scope.row.networkUnit }}
                  </span>
                  <span v-else>-</span>
                </template>
                <template v-slot:col-sysQty="scope">
                  <span v-if="scope.row.sysQty || scope.row.sysQty === 0">
                    {{ scope.row.sysQty + scope.row.unitName }}
                  </span>
                  <span v-else>-</span>
                </template>
                <template v-slot:col-price="scope">
                  <span v-if="scope.row.price || scope.row.price === 0">
                    {{ scope.row.price + '元/' + scope.row.networkUnit }}
                  </span>
                  <span v-else>-</span>
                </template>
                <template v-slot:col-sysPrice="scope">
                  <span v-if="scope.row.sysPrice || scope.row.sysPrice === 0">
                    {{ scope.row.sysPrice + '元/' + scope.row.unitName }}
                  </span>
                  <span v-else>-</span>
                </template>
                <template v-slot:col-provinceSumAmount="scope">
                  <span
                    v-if="
                      scope.row.provinceSumAmount ||
                      scope.row.provinceSumAmount === 0
                    "
                  >
                    {{ scope.row.provinceSumAmount + '元' }}
                  </span>
                  <span v-else>-</span>
                </template>
              </page-table>
            </el-form>
            <page-table
              v-else
              class="table-scroll-hidden"
              :refresh="summaryTableInfo.refresh"
              :init-curpage="summaryTableInfo.initCurpage"
              v-model:data="summaryTableInfo.data"
              :pager="false"
              :checkBox="false"
              :field-list="summaryTableInfo.fieldList"
              :row-class-name="tableRowClassName"
              :isDynamic="true"
            >
              <template v-slot:col-qty="scope">
                {{ scope.row.qty + scope.row.networkUnit }}
              </template>
              <template v-slot:col-networkUnitScale="scope">
                {{
                  scope.row.systemUnitCoefficient +
                  scope.row.unitName +
                  '=' +
                  scope.row.networkUnitCoefficient +
                  scope.row.networkUnit
                }}
              </template>
              <template v-slot:col-provinceAvailableQty="scope">
                <span
                  v-if="
                    scope.row.provinceAvailableQty ||
                    scope.row.provinceAvailableQty === 0
                  "
                >
                  {{ scope.row.provinceAvailableQty + scope.row.networkUnit }}
                </span>
                <span v-else>-</span>
              </template>
              <template v-slot:col-sysQty="scope">
                <span v-if="scope.row.sysQty || scope.row.sysQty === 0">
                  {{ scope.row.sysQty + scope.row.unitName }}
                </span>
                <span v-else>-</span>
              </template>
              <template v-slot:col-price="scope">
                <span v-if="scope.row.price || scope.row.price === 0">
                  {{ scope.row.price + '元/' + scope.row.networkUnit }}
                </span>
                <span v-else>-</span>
              </template>
              <template v-slot:col-sysPrice="scope">
                <span v-if="scope.row.sysPrice || scope.row.sysPrice === 0">
                  {{ scope.row.sysPrice + '元/' + scope.row.unitName }}
                </span>
                <span v-else>-</span>
              </template>
              <template v-slot:col-provinceSumAmount="scope">
                <span
                  v-if="
                    scope.row.provinceSumAmount ||
                    scope.row.provinceSumAmount === 0
                  "
                >
                  {{ scope.row.provinceSumAmount + '元' }}
                </span>
                <span v-else>-</span>
              </template>
            </page-table>
          </div>

          <!-- 选择产品 -->
          <AddProduct
            v-if="productInfo.visible"
            v-model:show-dialog="productInfo.visible"
            :query="productInfo.query.queryMap"
            :query-params="productInfo.query.queryParams"
            :api="productInfo.api"
            :table-key="productInfo.tableKey"
            :title="'选择产品'"
            :showPrice="$permission('provincePurch:price')"
            @callback="selectProductCallback"
          />
          <AddProduct
            v-if="importPurchOrderInfo.visible"
            v-model:show-dialog="importPurchOrderInfo.visible"
            :query="importPurchOrderInfo.query.queryMap"
            :query-params="importPurchOrderInfo.query.queryParams"
            :api="importPurchOrderInfo.api"
            :table-key="importPurchOrderInfo.tableKey"
            :title="'选择采购订单产品'"
            :defaultQty="true"
            :showPrice="$permission('provincePurch:price')"
            @callback="importPurchOrderCallback"
          />

          <select-supplier
            v-if="selectSupplierInfo.visible"
            v-model:show-dialog="selectSupplierInfo.visible"
            :query="selectSupplierInfo.query"
            :check-box="false"
            :saveEmpty="true"
            :highlight-row="true"
            :api="selectSupplierInfo.api"
            @callback="selectSupplierCallback"
          />
          <!-- 选择收货地址 -->
          <select-receive-address
            v-if="selectReceiveAddressInfo.visible"
            v-model:show-dialog="selectReceiveAddressInfo.visible"
            :query="selectReceiveAddressInfo.query"
            :check-box="false"
            :highlight-row="true"
            @callback="selectReceiveAddressCallback"
          />
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="provincePurchModify">
import { fatchPurchOrdersDetailListCustomizeListPage } from '@/api/purch'
import {
  getReceiveAddressPage,
  getSupplierProductPage,
  getProductCustomizeList,
  getSupplierPage,
} from '@/api/core'
import {
  createProvincePurchOrder,
  createProvincePurchOrderAndSave,
  updateProvincePurchOrder,
  getProvincePurchOrderById,
  getProvincePurchOrderDetailExtCustomizeListAll,
} from '@/api/province'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { getMappingTripartiteSupplierPage } from '@/api/tripartite'
import _ from 'lodash'
import AddProduct from './addProduct'
import SelectSupplier from '@/views/province/components/selectSupplier'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'title', 'orderId'])
const toSummaryFlag = ref(false) //切换到汇总页：否
const formRefs = ref([])
//用于显示取值
const systemConfig = ref(proxy.$store.state.permission.systemConfig)

const formInfo = ref({
  ref: null,
  data: {
    purchType: 1,
  },
  fieldList: [
    {
      label: '采购类型',
      value: 'purchType',
      type: 'select-model',
      code: 'province_purch_type',
      event: 'purchType',
    },
    { label: '订单名称', value: 'orderName', type: 'input' },
    { label: '供应商', value: 'supplierName', type: 'slot' },
    { label: '收货地址', value: 'address', type: 'slot' },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    orderName: [{ required: true, message: '请输入订单名称', target: 'blur' }],
    address: [{ required: true, message: '请选择收货地址', target: 'change' }],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  list: [
    { type: 'slot', label: '手动新增', value: 'addProduct' },
    { type: 'slot', label: '引用系统采购单', value: 'importPurchOrder' },
    { type: 'slot', label: '删除产品', value: 'removeProduct' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '删除产品',
        event: removeProduct,
        show: true,
      },
    ],
  },
})
//汇总页表格
const summaryTableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  fieldList: [],
})
const fullInfo = ref({
  btnList: [{ label: '保存并提交', event: saveAndSubmit, show: !props.orderId && proxy.$permission('provincePurch:saveAndSubmit')},{ label: '保存', event: save, show: true }],
})
//手动新增产品相关
const productInfo = ref({
  visible: false,
  api: getProductCustomizeList,
  tableKey:
    'productPageForProvincePurchOrder-com.slip.spd.entity.vo.core.CoreProductVONew',
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      status: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      supplierId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },

      isSunPurchase: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
      networkProductType: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      putShelfStatus: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
            type: {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
    },
    queryParams: {
      isProvinceQuery: 1,
      tsSystemCode: null,
      provinceSupplierId: null,
    },
  },
  searchList: [],
})
const importPurchOrderInfo = ref({
  visible: false,
  api: fatchPurchOrdersDetailListCustomizeListPage,
  tableKey:
    'provincePurchOrderDetailAddList-com.slip.spd.entity.vo.purch.PurchOrderDetailVO',
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '4,13,14,15',
      },
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      supplierId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },

      isSunPurchase: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
      networkProductType: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      isProvinceQuery: 1,
      provincePurchOrderId: null,
      productType: null,
      tsSystemCode: null,
      provinceSupplierId: null,
    },
  },
  searchList: [],
})
const selectSupplierInfo = ref({
  visible: false,
  api: getMappingTripartiteSupplierPage,
  query: {
    sort: 'create_time desc',
    tsSystemCode:
      proxy.$store.state.permission.systemConfig
        .connect_purchase_platform_system,
    reserved1: '', //试剂or1耗材
  },
})

const selectRow = ref('')
const selectReceiveAddressInfo = ref({
  visible: false,
  query: {},
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

const canAddProduct = computed(() => {
  return toSummaryFlag.value || !formInfo.value.data.supplierName
})
const canAddImportProduct = computed(() => {
  return toSummaryFlag.value
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length && !toSummaryFlag.value
})

watch(
  () => tableInfo.value.data,
  () => {
    tableInfo.value.data.forEach((row) => {
      row.key = row.productId + '&' + row.supplierId

      row.provinceSumAmount = proxy.$fn.accMul(row.qty || 0, row.price || 0)
    })
  },
  {
    deep: true,
  }
)
watch(
  () => toSummaryFlag.value,
  (val) => {
    if (val) {
      //汇总页面按照产品和供应商汇总展示
      let data = proxy.$fn.deepClone(tableInfo.value.data)

      summaryTableInfo.value.data = mergeData(data)
    }
  },
  {
    deep: true,
  }
)
watch(
  () => formInfo.value.data.purchType,
  () => {
    if (formInfo.value.data.purchType == 1) {
      tableInfo.value.fieldList.forEach((item) => {
        if (item.value === 'procureCatalogId') {
          item.hidden = true
        }
      })
      summaryTableInfo.value.fieldList.forEach((item) => {
        if (item.value === 'procureCatalogId') {
          item.hidden = true
        }
      })
    } else {
      tableInfo.value.fieldList.forEach((item) => {
        if (item.value === 'procureCatalogId') {
          item.hidden = false
        }
      })
      summaryTableInfo.value.fieldList.forEach((item) => {
        if (item.value === 'procureCatalogId') {
          item.hidden = false
        }
      })
    }
  },
  {
    deep: true,
    immediate: true,
  }
)
onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  //请求默认地址并回填
  getReceiveAddressPage({ isDefault: '1' }).then((resp) => {
    if (resp && resp.success && resp.data[0]) {
      formInfo.value.data.address = resp.data[0].addressValue
    }
  })
})

setData()
function setData() {
  let obj = {
    qty: {
      label: '数量',
      value: 'qty',
      type: 'slot',
      minWidth: '250px',
      hidden: true,
    },
    sysQty: {
      label: '系统采购数量',
      value: 'sysQty',
      type: 'slot',
      hidden: true,
    },
    provinceAvailableQty: {
      label: '省采可采购数量',
      value: 'provinceAvailableQty',
      type: 'slot',
      hidden: true,
    },
    price: {
      label: '单价',
      value: 'price',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('provincePurch:price'),
      hidden: true,
    },
    sysPrice: {
      label: '系统单价',
      value: 'sysPrice',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('provincePurch:price'),
      hidden: true,
    },
    provinceSumAmount: {
      label: '省采金额',
      value: 'provinceSumAmount',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('provincePurch:price'),
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      permission: !proxy.$permission('provincePurch:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
    provincePrice: {
      label: '省采单价',
      value: 'provincePrice',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('provincePurch:price'),
      hidden: true,
    },
    networkUnitScale: {
      label: 'SPD单位/省采单位',
      value: 'networkUnitScale',
      componentType: 'input',
      type: 'slot',
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  summaryTableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
  getCollectCustomize()
}
function mergeData(data) {
  //汇总页面按照产品和供应商汇总展示
  let afterData = []
  if (data && data.length) {
    let tempArr = []

    for (let i = 0; i < data.length; i++) {
      let str = data[i].productId + '&' + data[i].supplierId
      if (tempArr.indexOf(str) == -1) {
        afterData.push({
          ...data[i],
          extDetails: [data[i]],
        })
        tempArr.push(str)
      } else {
        for (let j = 0; j < afterData.length; j++) {
          if (
            afterData[j].productId == data[i].productId &&
            afterData[j].supplierId == data[i].supplierId
          ) {
            afterData[j].extDetails.push(data[i])

            break
          }
        }
      }
    }
    afterData.forEach((row) => {
      let qty = 0
      let provinceSumAmount = 0
      if (row.extDetails && row.extDetails.length) {
        row.extDetails.forEach((item) => {
          qty = proxy.$fn.accAdd(item.qty || 0, qty)
          provinceSumAmount = proxy.$fn.accAdd(
            item.provinceSumAmount || 0,
            provinceSumAmount
          )
        })
      }
      row.qty = qty
      row.provinceSumAmount = provinceSumAmount
    })
  }
  return afterData
}
function importPurchOrder() {
  //引用系统采购单
  let data = proxy.$fn.deepClone(tableInfo.value.data)
  data = data.filter(
    (item) => item.sysOrderDetailId && item.sysOrderDetailId !== -2
  )
  let idNotIn = data.map(function (item) {
    return item.sysOrderDetailId
  })
  importPurchOrderInfo.value.query.queryMap.id.value = idNotIn.toString()
  importPurchOrderInfo.value.query.queryParams.provinceSupplierId =
    formInfo.value.data.supplierId
  importPurchOrderInfo.value.query.queryMap.networkProductType.value =
    formInfo.value.data.purchType
  importPurchOrderInfo.value.query.queryParams.productType =
    formInfo.value.data.purchType
  importPurchOrderInfo.value.query.queryParams.tsSystemCode =
    proxy.$store.state.permission.systemConfig.connect_purchase_platform_system
  if (props.orderId) {
    importPurchOrderInfo.value.query.queryParams.provincePurchOrderId =
      props.orderId
  }
  importPurchOrderInfo.value.visible = true
}
function importPurchOrderCallback(rows) {
  //引用系统采购单返回
  if (rows) {
    rows = generateProductKey(rows)
    const data = rows.map(function (item) {
      return {
        ...item,
        sysOrderDetailId: item.id,
        sysPrice: item.price,
        price: item.provincePrice,
        sysQty: item.qty,
        qty: item.provinceCalcQty,
        sysOrderNo: item.orderNo,
      }
    })
    tableInfo.value.data = data.concat(tableInfo.value.data)
  }
}
function openSupplierWindow() {
  selectSupplierInfo.value.query.reserved1 = formInfo.value.data.purchType
  selectSupplierInfo.value.visible = true
}
function selectSupplierCallback(row) {
  if (row) {
    formInfo.value.data.supplierId = row.spdOrgId
    formInfo.value.data.supplierName = row.name
  } else {
    formInfo.value.data.supplierId = ''
    formInfo.value.data.supplierName = ''
  }
  tableInfo.value.data = []
}
function changeHandle(e, val) {
  if (e === 'purchType') {
    formInfo.value.data.supplierId = ''
    formInfo.value.data.supplierName = ''
    tableInfo.value.data = []
  }
}

function ifRenderValue(row) {
  return !(row.sysOrderDetailId && row.sysOrderDetailId !== -2)
}
function changeLarge(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function largeMax(row) {
  if (row.sysOrderDetailId && row.sysOrderDetailId !== -2) {
    return row.provinceAvailableQty
  } else {
    return 99999999
  }
}

// 触发事件
function handleEvent(event, data) {
  const _tableInfo = tableInfo.value
  switch (event) {
    case 'tableCheck':
      _tableInfo.selections = [...data]
      break
  }
}

//添加产品按钮
function addProduct() {
  let data = proxy.$fn.deepClone(tableInfo.value.data)
  data = data.filter(
    (item) => !(item.sysOrderDetailId && item.sysOrderDetailId !== -2)
  )
  let idNotIn = data.map(function (item) {
    return item.productId
  })
  productInfo.value.query.queryMap.networkProductType.value =
    formInfo.value.data.purchType
  productInfo.value.query.queryParams.tsSystemCode =
    proxy.$store.state.permission.systemConfig.connect_purchase_platform_system
  productInfo.value.query.queryMap.id.value = idNotIn.toString()
  productInfo.value.query.queryParams.provinceSupplierId =
    formInfo.value.data.supplierId
    // 药品
    productInfo.value.query.queryMap.type = {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryCategory: 'AND',
        queryResource: 0,
        queryType: 'EQUALS',
        value: formInfo.value.data.purchType == 3 ? 4 : 0,
      }
  productInfo.value.visible = true
}

function selectProductCallback(rows) {
  if (rows) {
    rows = generateProductKey(rows)
    const data = rows.map(function (item) {
      return {
        ...item,
        sysPrice: item.price,
        price: item.provincePrice,
        qty: item.editQty,
      }
    })
    tableInfo.value.data = data.concat(tableInfo.value.data)
  }
}
function generateProductKey(products) {
  return products.map((item) => {
    const key =
      item.productId +
      '&' +
      item.batchNumber +
      '&' +
      item.validityDate +
      '&' +
      item.productionDate
    item._id = key
    return item
  })
}
//删除产品
function removeProduct(item) {
  if (item) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (obj) => obj.id !== item.id
    )
    return
  }
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      tableInfo.value.selectionsCopy = proxy.$fn.deepClone(
        tableInfo.value.selections
      )
      tableInfo.value.data = tableInfo.value.data.filter(
        (row) => !tableInfo.value.selections.includes(row)
      )
    })
}
//打开选择收货地址窗口
function openReceiveAddressWindow() {
  selectReceiveAddressInfo.value.visible = true
}
function selectReceiveAddressCallback(data) {
  const _formInfo = formInfo.value
  if (data) {
    _formInfo.data.address = data.addressValue
  }
}

function saveAndSubmit() {
  save(true)
}
function save(isSaveAndSubmit) {
  const _tableInfo = tableInfo.value
  proxy.$fn.checkForm(formRefs.value).then(() => {
    if (!_tableInfo.data.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '产品不能为空',
      })
      return
    }
    checkSave(isSaveAndSubmit)
  })
}
function checkSave(isSaveAndSubmit) {
  const details = tableInfo.value.data
  const data = formInfo.value.data
  data.details = proxy.$fn.filterBlacklist(details)
  const api = data.id ? updateProvincePurchOrder : isSaveAndSubmit === true ? createProvincePurchOrderAndSave : createProvincePurchOrder
  api(data).then((resp) => {
    if (resp && resp.success) {
      emits('returnModify', false)
      showDialog.value = false
    }
  })
}
function getPurchOrderById(orderId) {
  getProvincePurchOrderById(orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data

      getPurchOrderDetails()
    }
  })
}
function getPurchOrderDetails() {
  getProvincePurchOrderDetailExtCustomizeListAll(filterInfo.value.query).then(
    (resp) => {
      if (resp && resp.success) {
        tableInfo.value.data = resp.data
      }
    }
  )
}

function tableRowClassName({ row = undefined }) {}

function getCustomize() {
  let param = {
    tableKey:
      'provincePurchOrderDetailExtModify-com.slip.spd.entity.vo.provincePlatform.ProvincePurchOrderDetailExtVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      filterInfo.value.query.customizeUserVO = data
      filterInfo.value.query.queryMap.orderId.value = props.orderId
      if (props.orderId) {
        getPurchOrderById(props.orderId)
      }
    }
  })
}
function getCollectCustomize() {
  //获取汇总表格的自定义
  let param = {
    tableKey:
      'provincePurchOrderDetailCollect-com.slip.spd.entity.vo.provincePlatform.ProvincePurchOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      summaryTableInfo.value.fieldList = proxy.$fn.setFieldList(
        summaryTableInfo.value.fieldList,
        data.detail
      )
    }
  })
}
</script>

<style scoped lang="scss">
// :deep(.table-scroll-hidden) > .el-table {
//   overflow-y: hidden;
// }
.model-panel-title {
  display: flex;
  align-items: center;
  .model-tips {
    display: flex;
    align-items: center;
    margin-left: 10px;
    color: #909399;
    .model-tips-nearly,
    .model-tips-expire {
      display: block;
      margin-left: 5px;
      width: 17px;
      height: 17px;
    }
    .model-tips-nearly {
      background: #fceacb;
    }
    .model-tips-expire {
      background: #f5e4e4;
    }
  }
}
:deep(.el-table) {
  .nearly-row {
    background: #fceacb;
  }
  .expire-row {
    background: #f5e4e4;
  }
  .cell-color {
    background: #f4aed9bd;
  }
}
</style>
